package cn.calm.application;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.log4j.Logger;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;

import cn.calm.application.service.IApplicationService;
import cn.calm.application.service.impl.ApplicationServiceImpl;
import cn.calm.commons.dao.IBaseDao;
import cn.calm.entity.Application;
@SuppressWarnings("rawtypes")
public class Activator implements BundleActivator {
	public static BundleContext context;
	private static Logger log=Logger.getLogger(Activator.class);
	private EntityManagerFactory emf;
	private EntityManager em;
	
	private ServiceRegistration<IApplicationService> applicationServiceReg;
	@Override
	public void start(BundleContext arg0) throws Exception {
		log.debug("starting");
		try {
			context=arg0;
			IApplicationService<Application> parameterService=new ApplicationServiceImpl<Application>();
			ServiceReference<IBaseDao> serviceRef= context.getServiceReference(IBaseDao.class);
			IBaseDao dao= context.getService(serviceRef);
			emf=Persistence.createEntityManagerFactory("entity");
			em=emf.createEntityManager();
			dao.setSession(em);
			parameterService.setBaseDao(dao);
			applicationServiceReg=context.registerService(IApplicationService.class, parameterService, null);
		} catch (Exception e) {
			log.error("",e);
		}finally{
			log.debug("started");
		}
	}

	@Override
	public void stop(BundleContext arg0) throws Exception {
		if(applicationServiceReg!=null){
			applicationServiceReg.unregister();
		}
		if(em!=null){
			em.close();
		}
		if(emf!=null){
			emf.close();
		}
		context=null;
	}
}
